package web.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import web.service.interfaces.WmsServiceInterface;
import map.beans.JqgridResponse;
import map.beans.WmsServerBean;

@Controller
@RequestMapping("/admin/map")
public class WmsController {
	private static Logger LOGGER = LoggerFactory.getLogger(WmsController.class);
	
	@Autowired
	WmsServiceInterface wmsManager;
	
	@RequestMapping(value = "/records", method = RequestMethod.GET)
	@ResponseBody
	@SuppressWarnings("unused")
	public JqgridResponse<WmsServerBean> records(@RequestParam("_search") Boolean search,
			@RequestParam(value = "filters", required = false) String filters,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord) {
		JqgridResponse<WmsServerBean> response = null;
		Pageable pageRequest = new PageRequest(page - 1, rows);
		
		try {
			if (sord != null) {
				Sort sort = null;
				sort = new Sort((sord.equals("asc") ? Direction.ASC : Direction.DESC), sidx);
				pageRequest = new PageRequest(page - 1, rows, sort);
				
			} else {
				pageRequest = new PageRequest(page - 1, rows);
			}

			List<WmsServerBean> mapServerDtos = wmsManager.findAllWms(); //propertiesFileService.getMapServers();

			response = new JqgridResponse<WmsServerBean>();
			response.setRows(mapServerDtos);
			response.setRecords(Integer.valueOf(mapServerDtos.size()).toString());
			response.setTotal(Integer.valueOf(1).toString());// pages total
			response.setPage(Integer.valueOf(1).toString());
			
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());

        }
		
        return response;
    }
	
	
	@RequestMapping(value="/msgs/{msg}", method = RequestMethod.GET)
	@ResponseBody
	public String getMessage(HttpServletRequest request, @PathVariable String msg) {
		LOGGER.debug(msg + "\n\n");
		
		return msg;
	}

}
